package com.infinit.easyreader.Biz;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Typeface;

import com.infinit.easyreader.utils.CommonUtils;
import com.infinit.easyreader.utils.Consts;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.text.DecimalFormat;
import java.util.Vector;

public class BookPageFactory implements Consts {


    DecimalFormat df;
    private MappedByteBuffer m_mbBuf = null;
    /**
     * 字节总长度
     */
    private int m_mbBufLen = 0;
    /**
     * 字节开始位置
     */
    private int m_mbBufBegin = 0;
    /**
     * 字节结束位置
     */
    private int m_mbBufEnd = 0;
    private String m_strCharsetName = "gbk";
    private Bitmap m_book_bg = null;
    private int mWidth;
    private int mHeight;
    /**
     * Vector<String> m_lines String型数组
     */
    private Vector<String> m_lines = new Vector<>();
    private int m_fontSize = FONT_SIZE;
    private int marginWidth = 20; // 左右与边缘的距离
    private int marginHeight = 25; // 上下与边缘的距离
    /**
     * 每页可以显示的行数
     */
    private int mLineCount; // 每页可以显示的行数
    private float mVisibleHeight; // 绘制内容的宽
    private float mVisibleWidth; // 绘制内容的宽

    // private int m_nLineSpaceing = 5;
    private int mLineSpacing = 7;
    private boolean m_isfirstPage, m_islastPage;
    private Paint mPaint;
    private Paint percentPaint;
    private Typeface fontFamily;


    public BookPageFactory(int w, int h) {
        mWidth = w;
        mHeight = h;
        // percentPaint.设置不变样式  ；写百分比专用
        percentPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        percentPaint.setTextAlign(Align.LEFT);
        percentPaint.setTextSize(18);//字体大小 24
        int m_textColor = Color.parseColor(INIT_TEXT_COLOR);
        percentPaint.setColor(m_textColor);
        // 下面是几个设置paint的。
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setTextAlign(Align.LEFT);
        mPaint.setTextSize(m_fontSize);
        mPaint.setColor(m_textColor);
        mPaint.setTypeface(fontFamily);
        mVisibleWidth = mWidth - marginWidth * 2;// 绘制内容的宽   上下左右的边缘都空一定的距离 所以*2
        mVisibleHeight = mHeight - marginHeight * 2;// 绘制内容的高
        mLineCount = (int) (mVisibleHeight / (m_fontSize + mLineSpacing)) - 1;
        // 可显示的行数 / 可显示的高度除于每个字体的高度
        df = new DecimalFormat("#0.0");
    }


    public void setFontFamily(Typeface fontFamily) {
        this.fontFamily = fontFamily;
    }

    public void setM_textColor(int m_textColor) {
        this.mPaint.setColor(m_textColor);
    }


    //这里获得了一个内存映像文件m_mbBuff
    public void openbook(String strFilePath) throws IOException {
        File book_file = new File(strFilePath);
        long lLen = book_file.length();//算是字节长度，有多少个字节
        m_mbBufLen = (int) lLen;//一样的
        //MappedByteBuffer 缓存
        m_mbBuf = new RandomAccessFile(book_file, "r").getChannel().map(FileChannel.MapMode.READ_ONLY, 0, lLen);
        //获取当前文件的charset
        m_strCharsetName = CommonUtils.getCharset(book_file);
    }

    //读取前一断落
    protected byte[] readParagraphBack(int nFromPos) {
        int i;
        byte b0, b1;
        switch (m_strCharsetName) {
            case "UTF-16LE":
                i = nFromPos - 2;
                while (i > 0) {
                    b0 = m_mbBuf.get(i);
                    b1 = m_mbBuf.get(i + 1);
                    if (b0 == 0x0a && b1 == 0x00 && i != nFromPos - 2) {
                        i += 2;
                        break;
                    }
                    i--;
                }

                break;
            case "UTF-16BE":
                i = nFromPos - 2;
                while (i > 0) {
                    b0 = m_mbBuf.get(i);
                    b1 = m_mbBuf.get(i + 1);
                    if (b0 == 0x00 && b1 == 0x0a && i != nFromPos - 2) {
                        i += 2;
                        break;
                    }
                    i--;
                }
                break;
            default:
                i = nFromPos - 1;// 之前的结束点， 往回获取

                while (i > 0) {
                    b0 = m_mbBuf.get(i);
                    if (b0 == 0x0a && i != nFromPos - 1) {
                        i++;
                        break;
                    }
                    i--;
                }
                break;
        }
        if (i < 0)
            i = 0;
        int nParaSize = nFromPos - i;
        int j;
        byte[] buf = new byte[nParaSize];
        for (j = 0; j < nParaSize; j++) {
            buf[j] = m_mbBuf.get(i + j);
        }
        return buf;
    }


    // 读取上一段落
    protected byte[] readParagraphForward(int nFromPos) {
        int i = nFromPos;
        byte b0, b1;
        // 根据编码格式判断换行
        if ("UTF-16LE".equals(m_strCharsetName)) {
            while (i < m_mbBufLen - 1) {
                b0 = m_mbBuf.get(i++);
                b1 = m_mbBuf.get(i++);
                if (b0 == 0x0a && b1 == 0x00) {
                    break;
                }
            }
        } else if (m_strCharsetName.equals("UTF-16BE")) {
            while (i < m_mbBufLen - 1) {
                b0 = m_mbBuf.get(i++);
                b1 = m_mbBuf.get(i++);
                if (b0 == 0x00 && b1 == 0x0a) {
                    break;
                }
            }
        } else {
            while (i < m_mbBufLen) {
                b0 = m_mbBuf.get(i++);
                if (b0 == 0x0a) {  // \r\n?
                    break;
                }
            }
        }
        int nParaSize = i - nFromPos;
        byte[] buf = new byte[nParaSize];
        for (i = 0; i < nParaSize; i++) {
            buf[i] = m_mbBuf.get(nFromPos + i);
        }
        return buf;
    }

    public Vector<String> pageDown() {
        String strParagraph = "";
        Vector<String> lines = new Vector<>();
        while (lines.size() < mLineCount && m_mbBufEnd < m_mbBufLen) {
            byte[] paraBuf = readParagraphForward(m_mbBufEnd); // 读取一个段落
            m_mbBufEnd += paraBuf.length;
            try {
                strParagraph = new String(paraBuf, m_strCharsetName);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            String strReturn = "";
            if (strParagraph.contains("\r\n")) {
                strReturn = "\r\n";
                strParagraph = strParagraph.replaceAll("\r\n", "");
            } else if (strParagraph.contains("\n")) {
                strReturn = "\n";
                strParagraph = strParagraph.replaceAll("\n", "");
            }

            if (strParagraph.length() == 0) {
                lines.add(strParagraph);
            }
            while (strParagraph.length() > 0) {
                int nSize = mPaint.breakText(strParagraph, true, mVisibleWidth, null);
                lines.add(strParagraph.substring(0, nSize));//
                strParagraph = strParagraph.substring(nSize);//
                if (lines.size() >= mLineCount) {
                    break;
                }
            }
            if (strParagraph.length() != 0) {
                try {
                    m_mbBufEnd -= (strParagraph + strReturn).getBytes(m_strCharsetName).length;
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return lines;//返回下一页的内容
    }

    //读取前一页的内容, 再把开始点=>结束点
    public void pageUp() {
        if (m_mbBufBegin < 0)
            m_mbBufBegin = 0;
        Vector<String> lines = new Vector<>();
        String strParagraph = "";
        while (lines.size() < mLineCount && m_mbBufBegin > 0) {
            Vector<String> paraLines = new Vector<>();
            byte[] paraBuf = readParagraphBack(m_mbBufBegin);
            m_mbBufBegin -= paraBuf.length;
            try {
                strParagraph = new String(paraBuf, m_strCharsetName);
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            strParagraph = strParagraph.replaceAll("\r\n", "");
            strParagraph = strParagraph.replaceAll("\n", "");

            if (strParagraph.length() == 0) {
                paraLines.add(strParagraph);
            }
            while (strParagraph.length() > 0) {
                int nSize = mPaint.breakText(strParagraph, true, mVisibleWidth,
                        null);
                paraLines.add(strParagraph.substring(0, nSize));
                strParagraph = strParagraph.substring(nSize);
            }
            lines.addAll(0, paraLines);
        }
        while (lines.size() > mLineCount) {
            try {
                m_mbBufBegin += lines.get(0).getBytes(m_strCharsetName).length;
                lines.remove(0);
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        m_mbBufEnd = m_mbBufBegin;

    }

    public void prePage() throws IOException {
        if (m_mbBufBegin <= 0) {
            m_mbBufBegin = 0;//第一页
            m_isfirstPage = true;
            return;
        }
        m_isfirstPage = false;
        m_lines.clear();//清空
        pageUp();// m_mbBufEnd = m_mbBufBegin;
        m_lines = pageDown();
    }

    public void nextPage() throws IOException {
        if (m_mbBufEnd >= m_mbBufLen) {
            m_islastPage = true;
            return;
        } else m_islastPage = false;
        m_lines.clear();
        m_mbBufBegin = m_mbBufEnd;//把之前的结尾地方 为下一个开始位置
        m_lines = pageDown();
    }


    public void onDraw(Canvas c) {
        if (m_lines.size() == 0)
            m_lines = pageDown();//初始化时为0
        if (m_lines.size() > 0) {
            c.drawBitmap(m_book_bg, 0, 0, null);
            int y = marginHeight;
            for (String strLine : m_lines) {//每读取一行就绘一行的文字起点是marginwidth,x,marginHeight+字体大小
                y += m_fontSize + mLineSpacing;
                c.drawText(strLine, marginWidth, y, mPaint);
            }
        }
        float fPercent = (float) (m_mbBufBegin * 1.0 / m_mbBufLen);
        String strPercent = df.format(fPercent * 100) + "%";
        int nPercentWidth = (int) percentPaint.measureText("999.9%") + 1;
        c.drawText(strPercent, mWidth - nPercentWidth, mHeight - 5, percentPaint);
    }

    public void setBgBitmap(Bitmap BG) {
        m_book_bg = BG;
    }

    public boolean isfirstPage() {
        return m_isfirstPage;
    }

    public boolean islastPage() {
        return m_islastPage;
    }


    // 下面是书签 需要使用到的两个数据
    public int getM_mbBufBegin() {
        return m_mbBufBegin;
    }

    public void setM_mbBufBegin(int m_mbBufBegin) {
        this.m_mbBufBegin = m_mbBufBegin;
    }

    public Vector<String> getM_lines() {
        return m_lines;
    }

    public int getM_mbBufEnd() {
        return m_mbBufEnd;
    }

    public void setM_mbBufEnd(int m_mbBufEnd) {
        this.m_mbBufEnd = m_mbBufEnd;
    }

    public void clearM_lines() {
        this.m_lines.clear();
    }

    public int getM_fontSize() {
        return m_fontSize;
    }

    public void setM_fontSize(int m_fontSize) {
        this.m_fontSize = m_fontSize;
        mPaint.setTextSize(m_fontSize);
        mLineCount = (int) (mVisibleHeight / (m_fontSize + mLineSpacing));
    }


    public String getQuote() {
        String quote = "";
        if (m_lines.size() != 0) {
            String firstLine = m_lines.get(0);
            quote = firstLine.trim().length() > 15 ? firstLine.substring(0, 15) : firstLine;
        }
        return quote;
    }
}
